package com.abou.mvc.editor;

import java.beans.PropertyEditorSupport;
import org.apache.commons.lang.StringUtils;
import com.abou.model.common.product.Sale;

/**
 * The property editor used to convert a country entities.
 * 
 * @author khalid
 */
public class SaleEditor extends PropertyEditorSupport {
  
  private static final String SEPARATOR = " ";
  
  /**
   * The constructor of the class
   */
  public SaleEditor() {

    super();
  }
  
  @Override
  public String getAsText() {

    return format((Sale) getValue());
  }
  
  /**
   * Formats the passed phone number
   * 
   * @param sale A phone number.
   * @return The string representation of a phone number.
   */
  public static String format(Sale sale) {

    String label = "";
    
    if (sale != null) {
      
      String percent = "";
      String price = "";
      
      if (sale.getPercent() != null) {
        
        percent = sale.getPercent().toString();
      }
      
      if (sale.getSalePrice() != null) {
        
        price = sale.getSalePrice().toString();
      }
      
      label = percent + SEPARATOR + price;
    }
    
    return label;
  }
  
  @Override
  public void setAsText(String text) {

    int percent = 0;
    double price = 0;
    
    if (!StringUtils.isBlank(text)) {
      
      String theText = text.trim();
      int pos = theText.indexOf(SEPARATOR);
      
      if (pos >= 0) {
        
        percent = Integer.valueOf(theText.substring(0, pos));
        
        if (pos < theText.length() - 1) {
          
          price = Double.valueOf(theText.substring(pos + 1, theText.length()));
        }
      }
    }
    
    setValue(new Sale(percent, price));
  }
}
